/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.service.table.impl;

import com.google.common.collect.Lists;
import com.je.common.base.util.StringUtil;
import com.je.meta.model.view.ViewColumn;
import com.je.meta.service.table.BuildAssociationDDLService;
import com.je.meta.service.table.Entry;
import org.springframework.stereotype.Service;

import java.util.*;

@Service("conventionAndJoinDDLService")
public class BuildConventionAndJoinDDLServiceImpl implements BuildAssociationDDLService {
    @Override
    public String createDdl(String template, List<ViewColumn> associationList) {
        Set<String> tableCodeList = new LinkedHashSet<>();
        StringBuilder whereSql = new StringBuilder();
        Map<String,String> map = new HashMap<>();
        String where="";
        List<String> join = Lists.newArrayList(
                "LEFT JOIN","RIGHT JOIN"
        );
        List<String> dika = Lists.newArrayList(
                "JOIN"
        );
        List<String> convention = Lists.newArrayList(
                "=",">","<","!=",">=","<="
        );
        for(int i =0;i<associationList.size();i++){
            ViewColumn viewColumn = associationList.get(i);
            String mainTableCode = viewColumn.getMainTableCode();
            String targetTableCode = viewColumn.getTargetTableCode();
            String mainColumn = viewColumn.getMainColumn();
            String targetColumn = viewColumn.getTargetColumn();
            String formula = viewColumn.getFormula();
            if(StringUtil.isNotEmpty(mainTableCode)){
                tableCodeList.add(mainTableCode);
            }
            if(StringUtil.isNotEmpty(targetTableCode)&&!join.contains(formula)){
                tableCodeList.add(targetTableCode);
            }
            if(convention.contains(formula)){
                if(StringUtil.isNotEmpty(mainColumn) || StringUtil.isNotEmpty(targetColumn)){
                    where=" WHERE ";
                }
                if(StringUtil.isNotEmpty(whereSql.toString())){
                    whereSql.append(" AND ");
                }
                if(StringUtil.isNotEmpty(mainColumn)){
                    if(StringUtil.isNotEmpty(mainTableCode)){
                        whereSql.append(mainTableCode).append(".");
                    }
                    whereSql.append(mainColumn);
                }
                whereSql.append(formula);
                if(StringUtil.isNotEmpty(targetColumn)){
                    if(StringUtil.isNotEmpty(targetTableCode)){
                        whereSql.append(targetTableCode).append(".");
                    }
                    whereSql.append(targetColumn);
                }

            }

            if(join.contains(formula)){
                StringBuilder  joinDDL = new StringBuilder();
                joinDDL.append(mainTableCode).append(" ")
                        .append(formula).append(" ")
                        .append(targetTableCode).append(" ON ");
                if(StringUtil.isNotEmpty(mainTableCode)){
                    joinDDL.append(mainTableCode).append(".");
                }
                joinDDL.append(mainColumn);
                joinDDL.append("=");
                if(StringUtil.isNotEmpty(targetTableCode)){
                    joinDDL.append(targetTableCode).append(".");
                }
                joinDDL.append(targetColumn);
                map.put(mainTableCode,joinDDL.toString());
            }
        }
        String tableCodes = "";
        Iterator iterator = tableCodeList.iterator();
        while (iterator.hasNext()){
            String tableCode = iterator.next().toString();
            if(map.containsKey(tableCode)){
                tableCodes=tableCodes+map.get(tableCode)+",";
            }else {
                tableCodes=tableCodes+tableCode+",";
            }

        }
        tableCodes = tableCodes.substring(0,tableCodes.length()-1);
        return formatTemplate(template,
                Entry.build("tableCodes",tableCodes),
                Entry.build("whereSql",whereSql),
                Entry.build("where",where));
    }
}
